// ...existing code...
package handlers

import (
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

type OverviewStats struct {
	TotalBooks   int64   `json:"total_books"`
	TotalUsers   int64   `json:"total_users"`
	LoanedOut    int64   `json:"loaned_out"`
	OverdueCount int64   `json:"overdue_count"`
	TotalFines   float64 `json:"total_fines"`
}

type TopBorrowedItem struct {
	BookID uint   `json:"book_id"`
	Title  string `json:"title"`
	Count  int64  `json:"count"`
}

func Overview(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		var s OverviewStats
		db.Model(&Book{}).Count(&s.TotalBooks)
		db.Model(&User{}).Count(&s.TotalUsers)
		db.Model(&Book{}).Where("available = ?", false).Count(&s.LoanedOut)
		db.Model(&BorrowRecord{}).Where("returned = ? AND due_at < current_timestamp", false).Count(&s.OverdueCount)

		var total float64
		db.Model(&BorrowRecord{}).Select("COALESCE(SUM(fine),0)").Scan(&total)
		s.TotalFines = total

		c.JSON(http.StatusOK, s)
	}
}

func TopBorrowed(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		n := 10
		if cnt := c.Query("n"); cnt != "" {
			fmtN, err := strconv.Atoi(cnt)
			if err == nil && fmtN > 0 {
				n = fmtN
			}
		}

		type resRow struct {
			BookID uint
			Count  int64
			Title  string
		}
		var rows []resRow
		db.Raw(`
            SELECT b.book_id, COUNT(*) as count, bk.title
            FROM borrow_records b
            LEFT JOIN books bk ON b.book_id = bk.id
            GROUP BY b.book_id, bk.title
            ORDER BY count DESC
            LIMIT ?
        `, n).Scan(&rows)

		out := make([]TopBorrowedItem, 0, len(rows))
		for _, r := range rows {
			out = append(out, TopBorrowedItem{
				BookID: r.BookID,
				Title:  r.Title,
				Count:  r.Count,
			})
		}
		c.JSON(http.StatusOK, out)
	}
}
